package net.luoran.dvm.common.util;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.java.Log;
import net.luoran.dvm.entity.UserContent;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * @author ：M1nG
 * @date ：Created in 2020/11/6 10:46
 * @description： jwt 工具类
 * @version: 1.0
 */
@Log
public class JwtUtil {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    // 过期时间，这里设为30分钟
    private static final long EXPIRE_TIME = 30 * 60 * 1000;
    // 密钥
    private static final String SECRET = "M1nG";

    /**
     * 生成签名,自动过期
     *
     * @param userContentStr 用户对象
     * @return 加密后的token
     */
    public static String sign(String userContentStr) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET); //使用HS256算法
        String token = JWT.create() //创建令牌实例
                .withClaim("user", userContentStr)
                //.withSubject(name) //签名的主题
                .withExpiresAt(date) //过期时间
                .sign(algorithm); //签名
        return token;
    }

    /**
     * 校验token是否正确
     *
     * @param token 令牌
     * @return 是否正确
     */
    public static boolean verify(String token) {
        try {
            String userStr = getUser(token);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("user", userStr)
                    //.withSubject(name)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获得token中的user信息
     *
     * @return token中包含的名称
     */
    public static String getUser(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("user").asString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获得UserContent
     *
     * @return token中包含的名称
     */
    public static UserContent getUserContent() {
        UserContent user = null;
        try {
            String header = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader(TOKEN_HEADER);
            String token = header.replace(TOKEN_PREFIX, "");
            user = JSONUtil.toBean(new CiphertextUtil().decrypt(token), UserContent.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token不存在或已失效，请重新获取token");
        }
        return user;
    }


}
